import threading
import time
import tkinter as tk
from datetime import datetime, timedelta

import akshare as ak


# stock_monitor.py 中添加资源处理函数
import sys
import os

import pystray
import requests
from PIL import Image

# from kaipanla import headers


def resource_path(relative_path):
    """ 获取资源的绝对路径 """
    try:
        base_path = sys._MEIPASS  # PyInstaller临时文件夹
    except AttributeError:
        base_path = os.path.abspath(".")
    return os.path.join(base_path, relative_path)

# 使用示例
# icon_path = resource_path("../assets/icon.ico")

class StockMonitor:
    def __init__(self, root):
        self.root = root
        root.title("A股实时情绪指标监控工具(云梦路小贤开发内部专用)")
        root.configure(bg='black')
        screen_width = root.winfo_screenwidth()
        screen_height = root.winfo_screenheight()
        x = (screen_width - 1950) // 2
        y = (screen_height - 30) // 2
        root.geometry(f"1950x30+{x}+{y}")
        self.is_topmost = tk.BooleanVar(value=True)
        self.root.attributes('-topmost', self.is_topmost.get())

        # 去掉标题栏
        self.root.overrideredirect(True)

        # 绑定鼠标事件以实现窗口拖动
        root.bind('<Button-1>', self.start_move)
        root.bind('<B1-Motion>', self.move_window)



        # 创建水平滚动容器
        self.container = tk.Canvas(root, bg='black', highlightthickness=0)
        self.scrollbar = tk.Scrollbar(root, orient="horizontal", command=self.container.xview)
        self.scroll_frame = tk.Frame(self.container, bg='black')

        self.container.configure(xscrollcommand=self.scrollbar.set)
        self.container.pack(side="top", fill="x", expand=True)
        self.scrollbar.pack(side="bottom", fill="x")

        self.container.create_window((0, 0), window=self.scroll_frame, anchor="nw")

        # self.btn_toggle = tk.Button(
        #     self.root,
        #     text="取消置顶",
        #     command=self.toggle_topmost,
        #     font=('微软雅黑', 8),  # 减小字体大小
        #     width=8,  # 设置按钮宽度
        #     height=1  # 设置按钮高度
        # )
        # # 使用 place 布局将按钮放在最右边
        # self.btn_toggle.place(relx=1, rely=0.5, anchor='e', x=-10)
        #
        # self.is_topmost.trace_add('write', self.update_button_text)



        # 初始化数据标签
        self.labels = {}
        self.last_request_time = 0
        self.request_interval = 5
        # columns = [
        #     '上涨', '涨>10%', '涨7~10%', '下跌','跌7~10%', '跌>10%',
        #     '当日成交额', '较昨日变动', '预测全天成交额', '涨停', '跌停', '炸板', '封板率', '昨首板溢价', '昨连板溢价', '更新时间'
        # ]
        columns = ['上证', '创业板',
            '上涨', '下跌',
            '当日成交额', '较昨日变动', '预测全天成交额', '涨停', '跌停', '炸板', '封板率', '昨首板溢价', '昨连板溢价',
            '更新时间'
        ]
        # columns2 = [
        #     '当日点评', '当日综合评分', '技术面' , '资金面'
        # ]

        self.row1_frame = tk.Frame(self.scroll_frame, bg='black')

        for col in columns:
            frame = tk.Frame(self.row1_frame, bg='black', padx=5)
            label = tk.Label(frame, text=f"{col}: --", font=('微软雅黑', 12),
                             fg='#FF1717', bg='black')
            label.pack()
            frame.pack(side='left', fill='x')
            self.labels[col] = label

        self.row1_frame.pack(side='top', fill='x')
        # # 空白分隔行
        # self.separator_frame = tk.Frame(self.scroll_frame, bg='black', height=10)  # 高度可以根据需要调整
        # self.separator_frame.pack(side='top', fill='x')

        # self.row2_frame = tk.Frame(self.scroll_frame, bg='black')
        # for col in columns2:
        #     frame = tk.Frame(self.row2_frame, bg='black', padx=5)
        #     label = tk.Label(frame, text=f"{col}: --", font=('微软雅黑', 12),
        #                      fg='#FF1717', bg='black')
        #     label.pack()
        #     frame.pack(side='left', fill='x')
        #     self.labels[col] = label
        # self.row2_frame.pack(side='top', fill='x')

        # 自动调整宽度
        self.scroll_frame.update_idletasks()
        self.container.config(scrollregion=self.container.bbox("all"))


        # 启动数据更新线程
        # self.update_data()
        self.schedule_update()
        # self.time_label = tk.Label(root, text="更新时间: --", font=('微软雅黑', 8), fg='yellow', bg='red')
        # self.time_label.pack(side='bottom', anchor='ne')
        # 创建任务栏图标
        # self.create_tray_icon()
        self.create_right_click_menu()

    # def create_tray_icon(self):
    #     image = Image.open(icon_path)
    #     menu = (pystray.MenuItem('退出', self.exit_app),)
    #     self.icon = pystray.Icon("StockMonitor", image, "A股实时情绪指标监控工具", menu)
    #     threading.Thread(target=self.icon.run, daemon=True).start()

    def create_right_click_menu(self):
        self.menu = tk.Menu(self.root, tearoff=0)
        self.menu.add_command(label="关闭", command=self.exit_app_from_menu)
        self.root.bind("<Button-3>", self.show_right_click_menu)

    def show_right_click_menu(self, event):
        try:
            self.menu.tk_popup(event.x_root, event.y_root)
        finally:
            self.menu.grab_release()

    def exit_app_from_menu(self):
        self.root.destroy()
        if hasattr(self, 'icon'):
            self.icon.stop()

    # def exit_app(self, icon, item):
    #     self.root.destroy()
    #     self.icon.stop()

    def exit_app(self, icon, item):
        self.root.destroy()
        self.icon.stop()

    def start_move(self, event):
        self.x = event.x
        self.y = event.y

    def move_window(self, event):
        deltax = event.x - self.x
        deltay = event.y - self.y
        x = self.root.winfo_x() + deltax
        y = self.root.winfo_y() + deltay
        self.root.geometry(f"+{x}+{y}")

    def toggle_topmost(self, event=None):
        new_state = not self.is_topmost.get()
        self.is_topmost.set(new_state)
        self.root.attributes('-topmost', new_state)
    def update_button_text(self, *args):
        self.btn_toggle.config(
            text=f"{'取消置顶' if self.is_topmost.get() else '启用置顶'}"
        )

    def schedule_update(self):
        # self.update_data()

        threading.Thread(target=self.update_data(), daemon=True).start()
        # self.root.after(60000, self.schedule_update)

    # def periodic_update(self):
    #     while True:
    #         self.update_data()
    #         time.sleep(30)  # 10秒更新一次

    # @staticmethod
    # def cal_up_down():
    #     try:
    #         print("正在获取实时数据...")
    #         # 获取实时行情数据
    #         try:
    #             df = ak.stock_zh_a_spot_em()
    #         except Exception as e:
    #             print(f"获取实时数据异常：{e}")
    #             df = ak.stock_zh_a_spot()
    #         print(f"获取实时数据成功...")
    #
    #         # 检查数据是否包含关键字段（避免字段名变更）
    #         if '涨跌幅' not in df.columns:
    #             raise KeyError("字段 '涨跌幅' 不存在，请检查接口返回的列名")
    #
    #         # 统计涨跌数量
    #         up_count = (df['涨跌幅'] > 0).sum()  # 上涨家数
    #         down_count = (df['涨跌幅'] < 0).sum()  # 下跌家数
    #         return up_count, down_count


            # 获取当前时间
            # current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")











            # 输出结果
            # print(f"更新时间：{current_time}")
            # print(f"上涨家数：{up_count}")
            # print(f"下跌家数：{down_count}")
            # print(f"总股票数：{len(df)}")
            # print(f"平盘家数：{len(df) - up_count - down_count}")  # 可选输出

        # except Exception as e:
        #     print(f"发生错误：{str(e)}")

    # @staticmethod
    # def get_realtime_zt_count():
    #     """获取实时涨停家数"""
    #     try:
    #         print("正在获取实时涨停数据...")
    #         date = datetime.now().strftime("%Y%m%d")
    #         zt_df = ak.stock_zt_pool_em(date=date)
    #         print(f"获取实时涨停数据成功...")
    #         return len(zt_df) if not zt_df.empty else 0
    #     except Exception as e:
    #         print(f"获取涨停数据异常：{e}")
    #         return 0

    # @staticmethod
    # def get_realtime_dt_count():
    #     """获取实时跌停家数"""
    #     try:
    #         print("正在获取实时跌停数据...")
    #         date = datetime.now().strftime("%Y%m%d")
    #         dt_df = ak.stock_zt_pool_dtgc_em(date=date)
    #         print(f"获取实时跌停数据成功...")
    #         return len(dt_df) if not dt_df.empty else 0
    #     except Exception as e:
    #         print(f"获取跌停数据异常：{e}")
    #         return 0

    # @staticmethod
    # def get_realtime_zb_count():
    #     try:
    #         print("正在获取实时炸板数据...")
    #         date = datetime.now().strftime("%Y%m%d")
    #         zb_df = ak.stock_zt_pool_zbgc_em(date=date)
    #         zb_df = zb_df[~zb_df['代码'].str.startswith(('43', '83', '87', '88'))]  # 北交所股票代码前缀为bj
    #         print(f"获取实时炸板数据成功...")
    #         return len(zb_df) if not zb_df.empty else 0
    #     except Exception as e:
    #         print(f"获取炸板数据异常：{e}")
    #         return 0

    def get_realtime_zb_count_v2(self):
        print("正在获取同花顺炸板池数据...")
        url = "https://data.10jqka.com.cn/dataapi/limit_up/open_limit_pool"
        # 查询参数
        params = {
            "page": 28,
            "limit": 15,
            "field": "199112,9002,48,1968584,19,3475914,9003,10,9004",
            "filter": "HS,GEM2STAR",
            # "date": (datetime.today() - timedelta(days=1)).strftime("%Y%m%d"),
            "order_field": "199112",
            "order_type": 0
        }

        headers = {
            "Host": "data.10jqka.com.cn",
            "Connection": "keep-alive",
            "sec-ch-ua-platform": "Android",
            "User-Agent": "Mozilla/5.0 (Linux; Android 15; 2410DPN6CC Build/AQ3A.240812.002; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/134.0.6998.135 Mobile Safari/537.36 Hexin_Gphone/11.26.02 (Royal Flush)",
            "Accept": "application/json, text/plain, */*",
            "sec-ch-ua": '"Chromium";v="134", "Not:A-Brand";v="24", "Android WebView";v="134"',
            "sec-ch-ua-mobile": "?1",
            "X-Requested-With": "com.hexin.plat.android",
            "Sec-Fetch-Site": "same-origin",
            "Sec-Fetch-Mode": "cors",
            "Sec-Fetch-Dest": "empty",
            "Referer": "https://data.10jqka.com.cn/mobile/limitup/v2/index.html",
            "Accept-Encoding": "gzip, deflate, br, zstd",
            "Accept-Language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7"
        }
        try:
            response = requests.get(
                url,
                params=params,
                headers=headers,
                verify=True  # 如需忽略SSL验证可改为False
            )
            # 从响应数据中提取关键指标
            response_data = response.json()
            # 从响应数据中提取关键指标
            # 假设 header_data 是从 response_data['data']['charts']['header'] 提取的
            zb_data_count = response_data['data']['page']['total']
            print(f"获取同花顺炸板池数据成功")
            return zb_data_count if zb_data_count else 0
        except Exception as e:
            print(f"获取同花顺炸板池数据失败: {e}")
            return None


    @staticmethod
    def get_today():
        today = datetime.now()
        # yesterday = today - timedelta(days=1)
        # if today.weekday() == 0:
        #     today -= timedelta(days=3)
        if today.weekday() == 6:
            today -= timedelta(days=2)
        elif today.weekday() == 5:
            today -= timedelta(days=1)
        return today.strftime("%Y%m%d")

    # @classmethod
    # def get_yestoday_zt(cls):
    #     try:
    #         print("正在获取昨日涨停数据...")
    #         # 获取昨日涨停数据
    #         trade_date = cls.get_today()
    #         limit_df = ak.stock_zt_pool_previous_em(date=trade_date)
    #
    #         print(f"获取昨日涨停数据成功...")
    #         print(f"******************************************************")
    #
    #         # 新增：过滤北交所股票（通过代码前缀过滤）
    #         limit_df = limit_df[~limit_df['代码'].str.startswith(('43', '83', '87', '88'))]  # 北交所股票代码前缀为bj
    #
    #         # 新增：过滤ST股票（通过名称字段）
    #         limit_df = limit_df[~limit_df['名称'].str.contains('ST', na=False)]  # 包含ST或*ST
    #
    #         # 统一代码格式（移除sh/sz/bj前缀）
    #         limit_df['代码'] = limit_df['代码'].str[2:]
    #
    #         if limit_df.empty:
    #             raise ValueError("昨日无有效涨停数据（已过滤北交所）")
    #
    #         return limit_df
    #
    #
    #     except Exception as e:
    #         print(f"获取数据失败: {e}")
    #         exit()

    @staticmethod
    def get_realtime_zf():
        try:
            print("获取指数数据")
            index_em_df = ak.stock_zh_index_spot_em('沪深重要指数')
            print(f"获取指数数据成功")
            return index_em_df if not index_em_df.empty else None
        except Exception as e:
            print(f"获取指数异常：{e}")
            return None

    def get_up_down_new(self):
        print("正在获取同花顺涨跌数据...")
        url = "https://dq.10jqka.com.cn/fuyao/up_down_distribution/distribution/v2/realtime"
        headers = {
            "Host": "dq.10jqka.com.cn",
            "Connection": "keep-alive",
            "sec-ch-ua-platform": "Android",
            "User-Agent": "Mozilla/5.0 (Linux; Android 15; 2410DPN6CC Build/AQ3A.240812.002; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/134.0.6998.135 Mobile Safari/537.36 Hexin_Gphone/11.26.02 (Royal Flush)",
            "Accept": "application/json, text/plain, */*",
            "sec-ch-ua": '"Chromium";v="134", "Not:A-Brand";v="24", "Android WebView";v="134"',
            "sec-ch-ua-mobile": "?1",
            "Origin": "https://eq.10jqka.com.cn",
            "X-Requested-With": "com.hexin.plat.android",
            "Sec-Fetch-Site": "same-site",
            "Sec-Fetch-Mode": "cors",
            "Sec-Fetch-Dest": "empty",
            "Referer": "https://eq.10jqka.com.cn/",
            "Accept-Encoding": "gzip, deflate, br, zstd",
            "Accept-Language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7"
            # "Cookie": "user=MDptb180Nzc0MjQzMzc6Ok5vbmU6NTAwOjQ4NzQyNDMzNzo1LDEsNDA7NiwxLDQwOzcsMTExMTExMTExMTEwLDQwOzgsMTExMTAxMTEwMDAwMTExMTEwMDEwMDEwMDEwMDAwMDAsNDA7MzMsMDAwMTAwMDAwMDAwLDIzNjszNiwxMDAxMTExMTAwMDAxMTAwMTAxMTExMTEsMjM2OzQ2LDAwMDAxMTExMTAwMDAwMTExMTExMTExMSwyMzY7NTEsMTEwMDAwMDAwMDAwMDAwMCwyMzY7NTgsMDAwMDAwMDAwMDAwMDAwMDEsMjM2Ozc4LDEsMjM2Ozg3LDAwMDAwMDAwMDAwMDAwMDAwMDAxMDAwMCwyMzY7MTE5LDAwMDAwMDAwMDAwMDAwMDAwMDEwMTAwMDAwMDAwMCwyMzY7MTI1LDExLDIzNjs0NCwxMSw0MDsxLDEwMSw0MDsyLDEsNDA7MywxLDQwOzEwMiwxLDQwOjI0Ojo6NDc3NDI0MzM3OjE3NDM2NDk1MDE6OjoxNTUxNDA3MDQwOjQ4OTI5OTowOjExMDA5YjUxOTViMzEyN2U3ZmJlOTE3MDgzM2ExNDg5MDo6MQ%3D%3D; userid=477424337; u_name=mo_477424337; escapename=mo_477424337; ticket=0b931e603ea0d3f4b6023f224bb4e79b; user_status=0; hxmPid=hqMarketPkgVersionControl; v=A7uJmuXpWDa08WSCjdpz8L6MS5QlEM8SySSTxq14l7rRDNRONeBfYtn0IxG-"
        }
        try:
            response = requests.get(
                url,
                # params=params,
                headers=headers,
                verify=True  # 如需忽略SSL验证可改为False
            )
            # 从响应数据中提取关键指标
            response_data = response.json()
            # 从响应数据中提取关键指标
            # 假设 header_data 是从 response_data['data']['charts']['header'] 提取的
            data = response_data['data']
            print(f"获取同花顺实时涨跌数据成功")
            return data
        except Exception as e:
            print(f"获取同花顺实时涨跌数据失败: {e}")
            return None



    def get_turnover(self):
        print("正在获取同花顺成交额数据...")
        url = "https://dq.10jqka.com.cn/fuyao/market_analysis_api/chart/v1/get_chart_data"
        params = {
            "chart_key": "turnover_minute"
        }

        headers = {
            "Host": "dq.10jqka.com.cn",
            "Connection": "keep-alive",
            "sec-ch-ua-platform": "Android",
            "User-Agent": "Mozilla/5.0 (Linux; Android 15; 2410DPN6CC Build/AQ3A.240812.002; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/134.0.6998.135 Mobile Safari/537.36 Hexin_Gphone/11.26.02 (Royal Flush)",
            "Accept": "application/json, text/plain, */*",
            "sec-ch-ua": '"Chromium";v="134", "Not:A-Brand";v="24", "Android WebView";v="134"',
            "sec-ch-ua-mobile": "?1",
            "Origin": "https://eq.10jqka.com.cn",
            "X-Requested-With": "com.hexin.plat.android",
            "Sec-Fetch-Site": "same-site",
            "Sec-Fetch-Mode": "cors",
            "Sec-Fetch-Dest": "empty",
            "Referer": "https://eq.10jqka.com.cn/",
            "Accept-Encoding": "gzip, deflate, br, zstd",
            "Accept-Language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7"
            # "Cookie": "user=MDptb180Nzc0MjQzMzc6Ok5vbmU6NTAwOjQ4NzQyNDMzNzo1LDEsNDA7NiwxLDQwOzcsMTExMTExMTExMTEwLDQwOzgsMTExMTAxMTEwMDAwMTExMTEwMDEwMDEwMDEwMDAwMDAsNDA7MzMsMDAwMTAwMDAwMDAwLDIzNjszNiwxMDAxMTExMTAwMDAxMTAwMTAxMTExMTEsMjM2OzQ2LDAwMDAxMTExMTAwMDAwMTExMTExMTExMSwyMzY7NTEsMTEwMDAwMDAwMDAwMDAwMCwyMzY7NTgsMDAwMDAwMDAwMDAwMDAwMDEsMjM2Ozc4LDEsMjM2Ozg3LDAwMDAwMDAwMDAwMDAwMDAwMDAxMDAwMCwyMzY7MTE5LDAwMDAwMDAwMDAwMDAwMDAwMDEwMTAwMDAwMDAwMCwyMzY7MTI1LDExLDIzNjs0NCwxMSw0MDsxLDEwMSw0MDsyLDEsNDA7MywxLDQwOzEwMiwxLDQwOjI0Ojo6NDc3NDI0MzM3OjE3NDM2NDk1MDE6OjoxNTUxNDA3MDQwOjQ4OTI5OTowOjExMDA5YjUxOTViMzEyN2U3ZmJlOTE3MDgzM2ExNDg5MDo6MQ%3D%3D; userid=477424337; u_name=mo_477424337; escapename=mo_477424337; ticket=0b931e603ea0d3f4b6023f224bb4e79b; user_status=0; hxmPid=hqMarketPkgVersionControl; v=A7uJmuXpWDa08WSCjdpz8L6MS5QlEM8SySSTxq14l7rRDNRONeBfYtn0IxG-"
        }
        try:
            response = requests.get(
                url,
                params=params,
                headers=headers,
                verify=True  # 如需忽略SSL验证可改为False
            )
            # 从响应数据中提取关键指标
            response_data = response.json()
            # 从响应数据中提取关键指标
            # 假设 header_data 是从 response_data['data']['charts']['header'] 提取的
            header_data = response_data['data']['charts']['header']
            print(f"获取同花顺成交额数据成功")
            return header_data
        except Exception as e:
            print(f"获取同花顺成交额数据失败: {e}")
            return None

    def get_marget_score(self):
        print("正在获取市场得分数据...")
        url = "https://dq.10jqka.com.cn/fuyao/market_analysis_api/score/v1/get_market_score"

        headers = {
            "Host": "dq.10jqka.com.cn",
            "Connection": "keep-alive",
            "sec-ch-ua-platform": "Android",
            "User-Agent": "Mozilla/5.0 (Linux; Android 15; 2410DPN6CC Build/AQ3A.240812.002; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/134.0.6998.135 Mobile Safari/537.36 Hexin_Gphone/11.26.02 (Royal Flush)",
            "Accept": "application/json, text/plain, */*",
            "sec-ch-ua": '"Chromium";v="134", "Not:A-Brand";v="24", "Android WebView";v="134"',
            "sec-ch-ua-mobile": "?1",
            "Origin": "https://eq.10jqka.com.cn",
            "X-Requested-With": "com.hexin.plat.android",
            "Sec-Fetch-Site": "same-site",
            "Sec-Fetch-Mode": "cors",
            "Sec-Fetch-Dest": "empty",
            "Referer": "https://eq.10jqka.com.cn/",
            "Accept-Encoding": "gzip, deflate, br, zstd",
            "Accept-Language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7"
            # "Cookie": "user=MDptb180NzOiQ2Mzc60k5vbmU6NTAwOjQ4NzQyNDMzNzo1LDESNDATNiwxLDQwOzcSMTExMTExMTExMTEwLDQwOzgsMTExMTAxMTEwMDAwMTExMTEwMDEwMDEwMDAwMDAsNDATMzMsMDAwMTAwMDAwMDAwLDizNjszNiwxMDAMTExMTAwMDAwMTAwMTAxMTExMTEsMjM2OzQ6LDAwMDAxMTExMTAwMDAwMTExMTExMTExMSwyMzY7NTEsMTEwMDAwMDAwMDAwMDAwMCwyMzY7NTgsMDAwMDAwMDAwMDAwMDEsMjM2OzC4LDEsMjM2Ozg3LDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMCwyMzY7MTE5LDAwMDAwMDAwMDAwMDAwMDAwMDEwMTAwMDAwMDAwMCwyMzY7MTILDExLDizNjsONCwxMSwOMDSxLDEWMSwOMDsyLDESNDATMywxLDQwOzEwMiwxLDQwOjIOojOsDc3NDIOMzM3OjE3NDM2NDkIMDE6OjoXNTUXNDA3MDQwOjQ4OTI5OTowOjExMDA5YjUxOTViMzEyNJZmJIOTE3MDgzM2EXNDg5MDo6MQ%3D%3D; userid=477424337; u_name=mo_477424337; escapename=mo_477424337; ticket=0b931e603ea0d3f4b6023f224bb4e79b; user_status=0; hxmPid=haMarketPkgVersionControl; v=A9vpOsVOJDXTOTipy97KJ5sazRFsO-y6cSzzsOYtlrxrPQuVYB_AvmUQ7He"
        }


        try:
            response = requests.get(
                url,
                headers=headers,
                verify=True  # 如需忽略SSL验证可改为False
            )
            # 从响应数据中提取关键指标
            response_data = response.json()
            # 从响应数据中提取关键指标
            # 假设 header_data 是从 response_data['data']['charts']['header'] 提取的
            score_data = response_data['data']
            print(f"获取同花顺市场分数数据成功")
            return score_data
        except Exception as e:
            print(f"获取同花顺市场分数数据失败: {e}")
            return None

    def fetch_data(self, code):
        # 补全 URL（原始链接被截断，推测完整路径）
        url = "https://dataq.10jqka.com.cn/fetch-data-server/fetch/v1/specific_data"

        # 修正后的请求头（过滤冗余字段）
        headers = {
            "Platform": "mobileweb",
            "Source-id": "constituent-stock",
            "Content-Length": "691",
            "Host": "dataq.10jqka.com.cn",
            "Connection": "Keep-Alive",
            "Accept-Encoding": "gzip",
            "User-Agent": "Mozilla/5.0 (Linux; Android 15; 2410DPN6CC Build/AQ3A.240812.002; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/134.0.6998.135 Mobile Safari/537.36 Hexin_Gphone/11.26.02 (Royal Flush)",
            "Content-Type": "application/json"  # 按实际类型调整
            # "Cookie": "user=H0p16R0NzOtMQ2Mzc0J6vbmU8NTAwQQAiXaQ; yNDMzNzuLDEsMDATNiKuADQwDZxFMTEeMTEeMTEeMTEeMLQQ; wQgapHTEeMTAoHTEeWbDAwMDDeMTEeMTEeWbDawMDDeWMDDeWMDAA",
            # 拼接多行 Cookie
        }

        # 若需要请求体（根据接口文档补充）
        payload = {
            "code_selectors": {
                "intersection": [
                    {
                        "type": "hq_block_code",
                        "values": [
                            f"48:{code}"
                        ]
                    }
                ]
            },
            "indexes": [
                {"index_id": "security_name"},
                {"index_id": "last_price"},
                {"index_id": "hq-fncdict-199112"},
                {"index_id": "hq-fncdict-3250"},
                {"index_id": "hq-fncdict-3475914"},
                {"index_id": "hq-fncdict-3541450"},
                {"index_id": "hq-fncdict-133957"},
                {"index_id": "hq-fncdict-527526"},
                {"index_id": "hq-fncdict-1968584"},
                {"index_id": "turnover"},
                {"index_id": "total_share_cnt", "time_type": "DAY_1", "timestamp": 0},
                {"index_id": "hq-fncdict-1771976"},
                {"index_id": "hq-fncdict-199189"},
                {"index_id": "F10-pb_mrq"},
                {"index_id": "hq-fncdict-526792"}
            ],
            "page_info": {
                "page_begin": 0,
                "page_size": 15,
                "code_begin": 0
            },
            "sort": [
                {"idx": 2, "type": "DESC"}
            ]
        }
        all_results = []
        page_begin = 0
        page_size = 15
        while True:
            payload["page_info"]["page_begin"] = page_begin
            payload["page_info"]["page_size"] = page_size
            try:
                response = requests.post(
                    url,
                    headers=headers,
                    json=payload,  # 或 data=payload（表单格式）
                    verify=True,  # SSL 验证
                    timeout=30  # 增加超时时间
                )
                response.raise_for_status()  # 自动检查 HTTP 错误
                print(f"状态码: {response.status_code}")
                data = response.json()['data']
                if "data" in data:
                    items = data["data"]
                    if not items:
                        break
                    all_results.extend(items)
                    page_begin += len(items)
                    print(f"已获取 {len(items)} 条数据")
                else:
                    print("未找到 'data' 字段")
                    break

            except requests.exceptions.SSLError:
                print("SSL 证书验证失败，可临时设置 verify=False（不推荐）")
                break
            except requests.exceptions.RequestException as e:
                print(f"请求异常: {e}")
                time.sleep(5)  # 等待一段时间后重试
                continue
        print(f"总共获取 {len(all_results)} 条记录")
        return all_results

    def cal_avg(self, stocks_data: list[dict]):
        if not stocks_data:
            return 0
        increases = []
        for stock in stocks_data:
            for item in stock["values"]:
                if item["idx"] == 2:
                    if item["value"] is not None:
                        increases.append(item["value"])
                        break  # 找到后立即跳出循环

        # 计算平均涨幅
        if increases:
            average_increase = sum(increases) / len(increases)
            return round(average_increase, 2)
            # print(f"所有股票的平均涨幅为: {average_increase:.4f}%")



    def update_data(self):
        try:
            print(datetime.now())
            # 获取主要指数数据
            # while time.time() - self.last_request_time < self.request_interval:
            #     time.sleep(1)
            index_em_df = self.get_realtime_zf()
            # self.last_request_time = time.time()

            sh_index = index_em_df[index_em_df['代码'] == '000001']['最新价'].values[0]
            sh_index_change = index_em_df[index_em_df['代码'] == '000001']['涨跌幅'].values[0]
            # sh_index_money = index_em_df[index_em_df['代码'] == '000001']['成交额'].values[0]
            # sz_index_money = index_em_df[index_em_df['代码'] == '399001']['成交额'].values[0]
            # bz_index_money = index_em_df[index_em_df['代码'] == '899050']['成交额'].values[0]
            cyb_index = index_em_df[index_em_df['代码'] == '399006']['最新价'].values[0]
            cyb_index_change = index_em_df[index_em_df['代码'] == '399006']['涨跌幅'].values[0]

            # # 获取市场统计数据的改进方案
            # ths_soup = self.get_ths_data()
            # market_container = ths_soup.select_one(".hcharts-list")
            #
            # # 获取涨停数据（使用新接口）
            # zt_count = ak.stock_zt_pool_em().shape[0]
            # dt_count = ak.stock_zt_pool_dt_em().shape[0]
            #
            # # 获取涨跌家数
            # sz_stats = ak.stock_szse_sector_summary(symbol="当日")
            # sh_stats = ak.stock_sse_summary()
            # while time.time() - self.last_request_time < self.request_interval:
            #     time.sleep(1)
            up_down_data = self.get_up_down_new()
            up = up_down_data.get('up', 0)
            down = up_down_data.get('down', 0)
            zt_count = up_down_data.get('limit_up', 0)
            dt_count = up_down_data.get('limit_down', 0)
            # down10 = up_down_data['table'][0].get('value', 0)
            # down710 = up_down_data['table'][1].get('value', 0)
            # up710 = up_down_data['table'][9].get('value', 0)
            # up10 = up_down_data['table'][10].get('value', 0)

            # self.last_request_time = time.time()
            # up, down = market_container.select_one(".cur .c-rise")
            # down = int(sh_stats['下跌数'].values[0]) + int(sz_stats['下跌家数'].values[0])
            #
            # 获取成交量（亿）
            header_data = self.get_turnover()
            turnover = round(next((item['val'] for item in header_data if item['key'] == 'turnover'), 0)/1e8, 2)
            # turnover_pre = round(next((item['val'] for item in header_data if item['key'] == 'turnover_pre'), 0)/1e8, 2)
            turnover_change = round(next((item['val'] for item in header_data if item['key'] == 'turnover_change'), 0)/1e8, 2)
            predict_turnover = round(next((item['val'] for item in header_data if item['key'] == 'predict_turnover'), 0)/1e8, 2)

            # score_data = self.get_marget_score()
            # score_title = score_data.get('score_content', 'N/A')
            # sum_score = score_data.get('sum_socre', 0)
            # finance_score = score_data.get('finance_score', 0)
            # tech_score = score_data.get('tech_score', 0)

            # volume = round((float(sh_stats['成交金额'].values[0]) +
            #                 float(sz_stats['成交金额'].values[0])) / 10000, 1)
            #
            # # 获取涨停数据
            # zt_df = ak.stock_zt_pool_em()
            # while time.time() - self.last_request_time < self.request_interval:
            #     time.sleep(1)
            # zt_count = self.get_realtime_zt_count()

            # self.last_request_time = time.time()
            # while time.time() - self.last_request_time < self.request_interval:
            #     time.sleep(1)
            # dt_count = self.get_realtime_dt_count()
            # self.last_request_time = time.time()
            # while time.time() - self.last_request_time < self.request_interval:
            #     time.sleep(1)

            zb_count = self.get_realtime_zb_count_v2()
            # self.last_request_time = time.time()
            #
            # # 封板率（示例计算）
            # fbl = round(zt_count/(zt_count+zb_count)*100)

            # 计算封板率，避免除以零错误
            if zt_count + zb_count == 0:
                fbl = 0
            else:
                fbl = round(zt_count / (zt_count + zb_count) * 100)

            #
            # # A50期指
            # a50_df = ak.stock_zh_futures_spot()
            # a50 = a50_df[a50_df['symbol'] == 'A50期指']['最新价'].values[0]
            #
            # # 昨日指数（需要爬虫备用方案）
            # zs_data = self.get_yesterday_data()
            # while time.time() - self.last_request_time < self.request_interval:
            #     time.sleep(1)
            # limit_df = self.get_yestoday_zt()
            # self.last_request_time = time.time()
            # first_limit = limit_df[limit_df['昨日连板数'] == 1]
            first_limit_v2 = self.fetch_data("883993")
            # cont_limit = limit_df[limit_df['昨日连板数'] >= 2]
            cont_limit_v2 = self.fetch_data("883988")

            # 计算平均值（保留有效数据）
            # avg_first = first_limit['涨跌幅'].mean() if not first_limit.empty else 0
            avg_first_v2 = self.cal_avg(first_limit_v2)
            # avg_cont = cont_limit['涨跌幅'].mean() if not cont_limit.empty else 0
            avg_cont_v2 = self.cal_avg(cont_limit_v2)

            # volume = round((float(sh_index_money) + float(sz_index_money) + float(bz_index_money)) / 100000000, 2)

            # print(f"昨日首板数量：{len(first_limit)}（不含北交所）")
            # print(first_limit)
            # print(f"昨日连板数量：{len(cont_limit)}（不含北交所）")
            # print(cont_limit)
            # print("\n【今日实时统计】")
            # print(f"首板平均涨跌幅: {avg_first:.2f}%")
            # print(f"连板平均涨跌幅: {avg_cont:.2f}%")


            # 更新界面
            self.root.after(0, self.update_gui, {
                '上证': f"{sh_index:.2f}: {sh_index_change:.2f}%",
                '创业板': f"{cyb_index:.2f}: {cyb_index_change:.2f}%",
                '上涨': up,
                # '涨>10%': up10,
                # '涨7~10%': up710,
                '下跌': down,
                # '跌>10%': down10,
                # '跌7~10%': down710,
                '当日成交额': f"{turnover}亿",
                # '昨日成交额': f"{turnover_pre}亿",
                '较昨日变动': f"{turnover_change:.2f}亿",
                '预测全天成交额': f"{predict_turnover}亿",
                # '预估成交量': 0,
                # '情绪指数': 0,
                '涨停': zt_count,
                '跌停': dt_count,
                '炸板': zb_count,
                '封板率': f"{fbl}%",
                # 'A50期指': f"{a50:.2f}",
                # '昨首板家数': len(first_limit),
                '昨首板溢价': f"{avg_first_v2}%",
                # '昨连板家数': len(cont_limit),
                '昨连板溢价': f"{avg_cont_v2}%",
                '更新时间': datetime.now().strftime("%H:%M:%S"),
                # '当日点评': score_title,
                # '当日综合评分': sum_score,
                # '资金面': finance_score,
                # '技术面': tech_score,
            })

        except Exception as e:
            print("数据获取失败:", e)
        finally:
            self.root.after(5000, self.update_data)

    def update_gui(self, data):
        current_time = datetime.now().strftime("%H:%M:%S")
        # self.time_label.config(text=f"更新时间: {current_time}")
        for key in self.labels:
            value = data.get(key, '--')
            self.labels[key].config(text=f"{key}: {value}")


if __name__ == "__main__":
    root = tk.Tk()
    app = StockMonitor(root)
    root.mainloop()